package com.anti.modular.bus.billotherrevenues.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.anti.commom.core.utils.DecimalUtils;
import com.anti.core.context.login.LoginContextHolder;
import com.anti.core.utils.IdFlowingUtil;
import com.anti.jdbc.DBUtils;
import com.anti.jdbc.support.page.PageParam;
import com.anti.jdbc.support.page.PageResult;
import com.anti.commom.core.exception.BusinessException;
import com.anti.modular.bus.billotherrevenues.entity.BillOtherRevenues;
import com.anti.modular.bus.billotherrevenues.enums.BillOtherRevenuesExceptionEnum;
import com.anti.modular.bus.billotherrevenues.param.BillOtherRevenuesParam;
import com.anti.modular.bus.billotherrevenues.result.HjRes;
import com.anti.modular.bus.billotherrevenues.service.BillOtherRevenuesService;
import com.anti.modular.bus.billwater.entity.BillWater;
import com.anti.modular.bus.billwater.entity.BillWaterRoom;
import com.anti.modular.bus.billwater.service.BillWaterService;
import com.anti.modular.bus.billwaterdetail.entity.BillWaterDetail;
import com.anti.modular.bus.billwaterdetail.service.BillWaterDetailService;
import com.anti.modular.bus.housebill.entity.HouseBill;
import com.anti.modular.bus.housebilldetail.result.HouseBillDetailResult;
import com.anti.modular.bus.houselease.entity.HouseLease;
import com.anti.modular.sys.auth.pojo.SysLoginUser;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 其他收支service接口实现类
 *
 * @author anti
 * @date 2021-06-03 09:34:42
 */
@Service
public class BillOtherRevenuesServiceImpl implements BillOtherRevenuesService {
    @Resource
    DBUtils dbUtils;
    @Resource
    BillWaterService billWaterService;
    @Resource
    BillWaterDetailService billWaterDetailService;

    @Override
    public BillOtherRevenues getById(BillOtherRevenuesParam billOtherRevenuesParam){
        String sql="select * from bill_other_revenues where id =? ";
        return dbUtils.get(sql,BillOtherRevenues.class,billOtherRevenuesParam.getId());
    }

    @Override
    public PageResult page(PageParam pageParam,BillOtherRevenuesParam billOtherRevenuesParam) {
        StringBuilder sb=new StringBuilder("select * from bill_other_revenues where status = 0 ");
        ArrayList<Object> param = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(billOtherRevenuesParam)) {
            String searchType = billOtherRevenuesParam.getSearchType();
            if ("1".equals(searchType)){
                sb.append(" and revenues_status = 0");
                Integer type = billOtherRevenuesParam.getType();
                if(ObjectUtil.isNotEmpty(type)) {
                    if (type.intValue()!=0){
                        sb.append(" and type =? ");
                        param.add(type);
                    }
                }
            }else {
                sb.append(" and revenues_status = 1");
                String dateStrStart = billOtherRevenuesParam.getDateStrStart();
                String dateStrEnd = billOtherRevenuesParam.getDateStrEnd();
                if(ObjectUtil.isNotEmpty(dateStrStart)&&ObjectUtil.isNotEmpty(dateStrEnd)) {
                    // 根据房间名 查询
                    sb.append(" and  DATE_FORMAT(receive_date,'%Y-%m-%d')<=DATE_FORMAT(?,'%Y-%m-%d') and DATE_FORMAT(receive_date,'%Y-%m-%d')>=DATE_FORMAT(?,'%Y-%m-%d')");
                    param.add(dateStrEnd);
                    param.add(dateStrStart);
                }
                if (ObjectUtil.isNotEmpty(billOtherRevenuesParam.getBillInOutType())) {
                    int billInOutType = billOtherRevenuesParam.getBillInOutType();
                    if (0!=billInOutType){
                        sb.append(" and bill_in_out_type = ?");
                        param.add(billInOutType);
                    }
                }
                if (ObjectUtil.isNotEmpty(billOtherRevenuesParam.getCollectionType())) {
                    int transaction = billOtherRevenuesParam.getCollectionType();
                    if (0!=transaction){
                        sb.append(" and collection_type = ?");
                        param.add(transaction);
                    }
                }
            }
        }
        sb.append(" order by create_time desc ");
        return dbUtils.query(pageParam,sb.toString(),param.toArray());
    }

    @Override
    public List<BillOtherRevenues> list(BillOtherRevenuesParam billOtherRevenuesParam) {
        String sql="";
        return dbUtils.query(sql,BillOtherRevenues.class);
    }

    @Override
    public void add(BillOtherRevenuesParam billOtherRevenuesParam) {
        BillOtherRevenues billOtherRevenues = new BillOtherRevenues();
        BeanUtil.copyProperties(billOtherRevenuesParam, billOtherRevenues);
        int type = billOtherRevenues.getType();
        Date date = new Date();
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        if (type ==1||type==2){
            billOtherRevenues.setReceiveDate(billOtherRevenues.getShouldReceiveDate());
            billOtherRevenues.setRentReminderSwitch(0);
            billOtherRevenues.setRevenuesStatus(1);
            billOtherRevenues.setAuditId(sysLoginUser.getId());
            billOtherRevenues.setAuditName(sysLoginUser.getName());
            billOtherRevenues.setAuditTime(date);
        }else {
            billOtherRevenues.setRevenuesStatus(0);
        }
        if (type ==1||type ==3){
            billOtherRevenues.setBillInOutType(1);
        }else {
            billOtherRevenues.setBillInOutType(2);
        }
        String qtzd = IdFlowingUtil.getSnowflakesId("QTZD");
        billOtherRevenues.setNo(qtzd);
        billOtherRevenues.setStatus(0);
        billOtherRevenues.setCreateTime(date);
        billOtherRevenues.setManager(sysLoginUser.getName());
        billOtherRevenues.setCreateUser(sysLoginUser.getId());
        String key = dbUtils.insertKey(billOtherRevenues).toString();
        billOtherRevenues.setId(Long.parseLong(key));
        if (type ==1||type==2){
            int source=3;
            if (type == 2) {
                source = 4;
            }
            //保存流水账单
            BillWater billWaterParam = getBillWaterParam(billOtherRevenues,source,date,sysLoginUser.getId());
            Long billWaterKey = billWaterService.add(billWaterParam);
            //保存流水房間關聯表
            BillWaterRoom billWaterRoom=new BillWaterRoom();
            billWaterRoom.setBillWaterId(billWaterKey);
            billWaterRoom.setRoomId(billOtherRevenues.getRoomId());
            billWaterRoom.setRoomName(billOtherRevenues.getRoomName());
            billWaterRoom.setName(billOtherRevenues.getName());
            dbUtils.insert(billWaterRoom);
            //详情
            BillWaterDetail billWaterDetail=new BillWaterDetail();
            billWaterDetail.setBillInOutType(billOtherRevenues.getBillInOutType());
            billWaterDetail.setAmount(DecimalUtils.toBigDecimal(billOtherRevenues.getAmount()));
            billWaterDetail.setBillWaterId(billWaterKey);
            billWaterDetail.setName(billOtherRevenues.getRevenuesTypeName());
            billWaterDetail.setStatus(0);
            billWaterDetail.setCreateUser(sysLoginUser.getId());
            billWaterDetail.setCreateTime(date);
            billWaterDetailService.add(billWaterDetail);
        }
    }

    public void delete(Long id) {
        String sqls="select * from bill_other_revenues where id =? ";
        BillOtherRevenues billOtherRevenues = dbUtils.get(sqls, BillOtherRevenues.class, id);
        billOtherRevenues.setStatus(2);
        billOtherRevenues.setUpdateTime(new Date());
        billOtherRevenues.setUpdateUser(LoginContextHolder.me().getSysLoginUserId());
        dbUtils.update(billOtherRevenues);
        int revenuesStatus = billOtherRevenues.getRevenuesStatus();
        if (revenuesStatus == 1) {
            //删除流水详情
            billWaterService.deleteAllByType(billOtherRevenues.getId(),"bill_other_revenues");
        }
    }

    public void edit(BillOtherRevenuesParam billOtherRevenuesParam) {
        BillOtherRevenues billOtherRevenues = this.queryBillOtherRevenues(billOtherRevenuesParam);
        if (billOtherRevenues.getRevenuesStatus() ==1) {
            throw new BusinessException(0,"已到賬，請勿操作！");
        }
        String shouldReceiveDate = billOtherRevenuesParam.getShouldReceiveDate();
        billOtherRevenues.setShouldReceiveDate(DateUtil.parse(shouldReceiveDate,"yyyy-MM-dd"));
        billOtherRevenues.setAmount(billOtherRevenuesParam.getAmount());
        billOtherRevenues.setRentReminderSwitch(billOtherRevenuesParam.getRentReminderSwitch());
        billOtherRevenues.setRentReminderDay(billOtherRevenuesParam.getRentReminderDay());
        billOtherRevenues.setRentReminderHour(billOtherRevenuesParam.getRentReminderHour());
        billOtherRevenues.setRentReminderMinutes(billOtherRevenuesParam.getRentReminderMinutes());
        billOtherRevenues.setRemark(billOtherRevenuesParam.getRemark());
        billOtherRevenues.setUpdateUser(LoginContextHolder.me().getSysLoginUserId());
        billOtherRevenues.setUpdateTime(new Date());
        dbUtils.update(billOtherRevenues);
    }

    @Override
    public void editDaoZhang(BillOtherRevenuesParam billOtherRevenuesParam) {
        BillOtherRevenues billOtherRevenues = this.queryBillOtherRevenues(billOtherRevenuesParam);
        if (billOtherRevenues.getRevenuesStatus() ==1) {
            throw new BusinessException(0,"已到賬，請勿重複操作！");
        }
        Date date = new Date();
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        String receiveDate = billOtherRevenuesParam.getReceiveDate();
        billOtherRevenues.setCollectionType(billOtherRevenuesParam.getCollectionType());
        billOtherRevenues.setReceiveDate(DateUtil.parse(receiveDate,"yyyy-MM-dd"));
        billOtherRevenues.setRevenuesStatus(1);
        billOtherRevenues.setAuditId(sysLoginUser.getId());
        billOtherRevenues.setAuditName(sysLoginUser.getName());
        billOtherRevenues.setAuditTime(date);
        billOtherRevenues.setUpdateUser(sysLoginUser.getId());
        billOtherRevenues.setUpdateTime(date);
        dbUtils.update(billOtherRevenues);
        //生成流水
        Integer type = billOtherRevenues.getType();
        if (type ==3||type==4){
            int source=3;
            if (type == 4) {
                source = 4;
            }
            //保存流水账单
            BillWater billWaterParam = getBillWaterParam(billOtherRevenues,source,date,sysLoginUser.getId());
            Long billWaterKey = billWaterService.add(billWaterParam);
            //保存流水房間關聯表
            BillWaterRoom billWaterRoom=new BillWaterRoom();
            billWaterRoom.setBillWaterId(billWaterKey);
            billWaterRoom.setRoomId(billOtherRevenues.getRoomId());
            billWaterRoom.setRoomName(billOtherRevenues.getRoomName());
            billWaterRoom.setName(billOtherRevenues.getName());
            dbUtils.insert(billWaterRoom);
            //详情
            BillWaterDetail billWaterDetail=new BillWaterDetail();
            billWaterDetail.setBillInOutType(billOtherRevenues.getBillInOutType());
            billWaterDetail.setAmount(DecimalUtils.toBigDecimal(billOtherRevenues.getAmount()));
            billWaterDetail.setBillWaterId(billWaterKey);
            billWaterDetail.setName(billOtherRevenues.getRevenuesTypeName());
            billWaterDetail.setStatus(0);
            billWaterDetail.setCreateUser(sysLoginUser.getId());
            billWaterDetail.setCreateTime(date);
            billWaterDetailService.add(billWaterDetail);
        }
    }

    @Override
    public BillOtherRevenues detail(BillOtherRevenuesParam billOtherRevenuesParam) {
        return this.queryBillOtherRevenues(billOtherRevenuesParam);
    }

    @Override
    public BillOtherRevenues getLookDetail(Long id) {
        String sqls="select * from bill_other_revenues where id =? ";
        BillOtherRevenues billOtherRevenues = dbUtils.get(sqls, BillOtherRevenues.class, id);
        return billOtherRevenues;
    }

    @Override
    public HjRes getHjBySearchType(String searchType) {
        StringBuilder sb=new StringBuilder("SELECT (select  IFNULL(sum(amount),0) from bill_other_revenues" +
                " where status = 0 and revenues_status = ? and bill_in_out_type =1) as srhj,\n" +
                "(select IFNULL(sum(amount),0)  from bill_other_revenues " +
                "where status = 0 and revenues_status = ? and bill_in_out_type =2) as zchj from dual ");
        int revenuesStatus = 0;
        if ("2".equals(searchType)){
            revenuesStatus = 1;
        }
        return dbUtils.getFirst(sb.toString(),HjRes.class,revenuesStatus,revenuesStatus);
    }

    /**
     * 获取其他收支
     *
     * @author anti
     * @date 2021-06-03 09:34:42
     */
    private BillOtherRevenues queryBillOtherRevenues(BillOtherRevenuesParam billOtherRevenuesParam) {
        BillOtherRevenues billOtherRevenues = this.getById(billOtherRevenuesParam);
        if (ObjectUtil.isNull(billOtherRevenues)) {
            throw new BusinessException(BillOtherRevenuesExceptionEnum.NOT_EXIST);
        }
        return billOtherRevenues;
    }
    private BillWater getBillWaterParam(BillOtherRevenues billOtherRevenues,int source,Date date, Long sysLoginUserId ) {
        BillWater billWaterParam =new BillWater();
        billWaterParam.setRoomName(billOtherRevenues.getRoomName());
        billWaterParam.setName(billOtherRevenues.getName());
        billWaterParam.setSource(source);
        int billInOutType = billOtherRevenues.getBillInOutType();
        if (billInOutType==2){
            billWaterParam.setAmount(billOtherRevenues.getAmount().negate());
        }else {
            billWaterParam.setAmount(billOtherRevenues.getAmount());
        }
        billWaterParam.setReceiveDate(billOtherRevenues.getReceiveDate());
        billWaterParam.setShouldReceiveDate(billOtherRevenues.getShouldReceiveDate());
        billWaterParam.setOperatingDate(date);
        billWaterParam.setTransaction(billOtherRevenues.getCollectionType());
        billWaterParam.setManagerId(billOtherRevenues.getAuditId());
        billWaterParam.setManager(billOtherRevenues.getAuditName());
        billWaterParam.setManagertTime(billOtherRevenues.getAuditTime());
        billWaterParam.setAuditFlag(0);
        billWaterParam.setNo(billOtherRevenues.getNo());
        int type = billOtherRevenues.getType();
        if (type ==1||type==3){
            billWaterParam.setBillInOutType(1);
        }else {
            billWaterParam.setBillInOutType(2);
        }
        billWaterParam.setBillId(billOtherRevenues.getId());
        billWaterParam.setBillTable("bill_other_revenues");
        billWaterParam.setStatus(0);
        billWaterParam.setCreateUser(sysLoginUserId);
        billWaterParam.setCreateTime(date);
        return billWaterParam;
    }

}
